home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / answers / lisp-faq / part3 < prev    next >
Encoding:
Text File  |  1993-06-13  |  35.0 KB  |  786 lines

  1. Newsgroups: comp.lang.lisp,news.answers,comp.answers
  2. Path: senator-bedfellow.mit.edu!enterpoop.mit.edu!usc!math.ohio-state.edu!magnus.acs.ohio-state.edu!cis.ohio-state.edu!news.sei.cmu.edu!bb3.andrew.cmu.edu!crabapple.srv.cs.cmu.edu!mkant
  3. From: mkant+@cs.cmu.edu (Mark Kantrowitz)
  4. Subject: FAQ: Lisp Frequently Asked Questions 3/7 [Monthly posting]
  5. Message-ID: <lisp-faq-3.text_739958468@cs.cmu.edu>
  6. Followup-To: poster
  7. Summary: Common Pitfalls
  8. Sender: news@cs.cmu.edu (Usenet News System)
  9. Supersedes: <lisp-faq-3.text_737280178@cs.cmu.edu>
  10. Nntp-Posting-Host: a.gp.cs.cmu.edu
  11. Reply-To: lisp-faq@think.com
  12. Organization: School of Computer Science, Carnegie Mellon
  13. Date: Sun, 13 Jun 1993 08:01:17 GMT
  14. Approved: news-answers-request@MIT.Edu
  15. Expires: Sun, 25 Jul 1993 08:01:08 GMT
  16. Lines: 767
  17. Xref: senator-bedfellow.mit.edu comp.lang.lisp:10304 news.answers:9334 comp.answers:969
  18.  
  19. Archive-name: lisp-faq/part3
  20. Last-Modified: Mon Jun  7 17:07:57 1993 by Mark Kantrowitz
  21. Version: 1.34
  22.  
  23. ;;; ****************************************************************
  24. ;;; Answers to Frequently Asked Questions about Lisp ***************
  25. ;;; ****************************************************************
  26. ;;; Written by Mark Kantrowitz and Barry Margolin
  27. ;;; lisp-faq-3.text -- 35246 bytes
  28.  
  29. This post contains Part 3 of the Lisp FAQ.
  30.  
  31. If you think of questions that are appropriate for this FAQ, or would
  32. like to improve an answer, please send email to us at lisp-faq@think.com.
  33.  
  34. This section contains a list of common pitfalls. Pitfalls are aspects
  35. of Common Lisp which are non-obvious to new programmers and often
  36. seasoned programmers as well.
  37.  
  38. Common Pitfalls (Part 3):
  39.  
  40.   [3-0]  Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR
  41.          instead of BAR?  
  42.   [3-1]  Why can't it deduce from (READ-FROM-STRING "foobar" :START 3)
  43.          that the intent is to specify the START keyword parameter
  44.          rather than the EOF-ERROR-P and EOF-VALUE optional parameters?   
  45.   [3-2]  Why can't I apply #'AND and #'OR?
  46.   [3-3]  I used a destructive function (e.g. DELETE, SORT), but it
  47.          didn't seem to work.  Why? 
  48.   [3-4]  After I NREVERSE a list, it's only one element long.  After I
  49.          SORT a list, it's missing things.  What happened? 
  50.   [3-5]  Why does (READ-LINE) return "" immediately instead of waiting
  51.          for me to type a line?  
  52.   [3-6]  I typed a form to the read-eval-print loop, but nothing happened. Why?
  53.   [3-7]  DEFMACRO doesn't seem to work.
  54.          When I compile my file, LISP warns me that my macros are undefined
  55.          functions, or complains "Attempt to call <function> which is 
  56.          defined as a macro.
  57.   [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  58.   [3-9]  Closures don't seem to work properly when referring to the
  59.          iteration variable in DOLIST, DOTIMES and DO.
  60.   [3-10] What is the difference between FUNCALL and APPLY?
  61.   [3-11] Miscellaneous things to consider when debugging code.
  62.   [3-12] When is it right to use EVAL?
  63.   [3-13] Why does my program's behavior change each time I use it?
  64.   [3-14] When producing formatted output in Lisp, where should you put the
  65.          newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  66.          ~& vs ~% in FORMAT)?
  67.   [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  68.   [3-16] My program works when interpreted but not when compiled!
  69.  
  70. Search for \[#\] to get to question number # quickly.
  71.  
  72. ----------------------------------------------------------------
  73. Subject: [3-0] Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR 
  74.                instead of BAR?
  75.  
  76. READ-FROM-STRING is one of the rare functions that takes both &OPTIONAL and
  77. &KEY arguments:
  78.  
  79.        READ-FROM-STRING string &OPTIONAL eof-error-p eof-value 
  80.                                &KEY :start :end :preserve-whitespace
  81.  
  82. When a function takes both types of arguments, all the optional
  83. arguments must be specified explicitly before any of the keyword
  84. arguments may be specified.  In the example above, :START becomes the
  85. value of the optional EOF-ERROR-P parameter and 3 is the value of the
  86. optional EOF-VALUE parameter.
  87.      
  88. ----------------------------------------------------------------
  89. Subject: [3-1] Why can't it deduce from (READ-FROM-STRING "foobar" :START 3) 
  90.       that the intent is to specify the START keyword parameter rather than
  91.       the EOF-ERROR-P and EOF-VALUE optional parameters?
  92.  
  93. In Common Lisp, keyword symbols are first-class data objects.  Therefore,
  94. they are perfectly valid values for optional parameters to functions.
  95. There are only four functions in Common Lisp that have both optional and
  96. keyword parameters (they are PARSE-NAMESTRING, READ-FROM-STRING,
  97. WRITE-LINE, and WRITE-STRING), so it's probably not worth adding a
  98. nonorthogonal kludge to the language just to make these functions slightly
  99. less confusing; unfortunately, it's also not worth an incompatible change
  100. to the language to redefine those functions to use only keyword arguments.
  101.      
  102. ----------------------------------------------------------------
  103. Subject: [3-2] Why can't I apply #'AND and #'OR?
  104.  
  105. Here's the simple, but not necessarily satisfying, answer: AND and OR are
  106. macros, not functions; APPLY and FUNCALL can only be used to invoke
  107. functions, not macros and special operators.
  108.  
  109. OK, so what's the *real* reason?  The reason that AND and OR are macros
  110. rather than functions is because they implement control structure in
  111. addition to computing a boolean value.  They evaluate their subforms
  112. sequentially from left/top to right/bottom, and stop evaluating subforms as
  113. soon as the result can be determined (in the case of AND, as soon as a
  114. subform returns NIL; in the case of OR, as soon as one returns non-NIL);
  115. this is referred to as "short circuiting" in computer language parlance.
  116. APPLY and FUNCALL, however, are ordinary functions; therefore, their
  117. arguments are evaluated automatically, before they are called.  Thus, were
  118. APPLY able to be used with #'AND, the short-circuiting would be defeated.
  119.  
  120. Perhaps you don't really care about the short-circuiting, and simply want
  121. the functional, boolean interpretation.  While this may be a reasonable
  122. interpretation of trying to apply AND or OR, it doesn't generalize to other
  123. macros well, so there's no obvious way to have the Lisp system "do the
  124. right thing" when trying to apply macros.  The only function associated
  125. with a macro is its expander function; this function accepts and returns
  126. and form, so it cannot be used to compute the value.
  127.  
  128. The Common Lisp functions EVERY and SOME can be used to get the
  129. functionality you intend when trying to apply #'AND and #'OR.  For
  130. instance, the erroneous form:
  131.  
  132.    (apply #'and *list*)
  133.  
  134. can be translated to the correct form:
  135.  
  136.    (every #'identity *list*)
  137.  
  138. ----------------------------------------------------------------
  139. Subject: [3-3] I used a destructive function (e.g. DELETE, SORT), but 
  140.                it didn't seem to work.  Why?
  141.  
  142. I assume you mean that it didn't seem to modify the original list.  There
  143. are several possible reasons for this.  First, many destructive functions
  144. are not *required* to modify their input argument, merely *allowed* to; in
  145. some cases, the implementation may determine that it is more efficient to
  146. construct a new result than to modify the original (this may happen in Lisp
  147. systems that use "CDR coding", where RPLACD may have to turn a CDR-NEXT or
  148. CDR-NIL cell into a CDR-NORMAL cell), or the implementor may simply not
  149. have gotten around to implementing the destructive version in a truly
  150. destructive manner.  Another possibility is that the nature of the change
  151. that was made involves removing elements from the front of a list; in this
  152. case, the function can simply return the appropriate tail of the list,
  153. without actually modifying the list. And example of this is:
  154.      
  155.    (setq *a* (list 3 2 1))
  156.    (delete 3 *a*) => (2 1)
  157.    *a* => (3 2 1)
  158.  
  159. Similarly, when one sorts a list, SORT may destructively rearrange the
  160. pointers (cons cells) that make up the list. SORT then returns the cons
  161. cell that now heads the list; the original cons cell could be anywhere in
  162. the list. The value of any variable that contained the original head of the
  163. list hasn't changed, but the contents of that cons cell have changed
  164. because SORT is a destructive function:
  165.  
  166.    (setq *a* (list 2 1 3))
  167.    (sort *a* #'<) => (1 2 3)
  168.    *a* => (2 3)     
  169.  
  170. In both cases, the remedy is the same: store the result of the
  171. function back into the place whence the original value came, e.g.
  172.  
  173.    (setq *a* (delete 3 *a*))
  174.    *a* => (2 1)
  175.  
  176. Why don't the destructive functions do this automatically?  Recall
  177. that they are just ordinary functions, and all Lisp functions are
  178. called by value. They see the value of the argument, not the argument
  179. itself. Therefore, these functions do not know where the lists they
  180. are given came from; they are simply passed the cons cell that
  181. represents the head of the list. Their only obligation is to return
  182. the new cons cell that represents the head of the list. Thus
  183. "destructive" just means that the function may munge the list by
  184. modifying the pointers in the cars and cdrs of the list's cons cells.
  185. This can be more efficient, if one doesn't care whether the original
  186. list gets trashed or not.
  187.  
  188. One thing to be careful about when doing this (storing the result back
  189. into the original location) is that the original list might be
  190. referenced from multiple places, and all of these places may need to
  191. be updated.  For instance:
  192.  
  193.    (setq *a* (list 3 2 1))
  194.    (setq *b* *a*)
  195.    (setq *a* (delete 3 *a*))
  196.    *a* => (2 1)
  197.    *b* => (3 2 1) ; *B* doesn't "see" the change
  198.    (setq *a* (delete 1 *a*))
  199.    *a* => (2)
  200.    *b* => (3 2) ; *B* sees the change this time, though
  201.  
  202. One may argue that destructive functions could do what you expect by
  203. rearranging the CARs of the list, shifting things up if the first element
  204. is being deleted, as they are likely to do if the argument is a vector
  205. rather than a list.  In many cases they could do this, although it would
  206. clearly be slower.  However, there is one case where this is not possible:
  207. when the argument or value is NIL, and the value or argument, respectively,
  208. is not.  It's not possible to transform the object referenced from the
  209. original cell from one data type to another, so the result must be stored
  210. back.  Here are some examples:
  211.  
  212.    (setq *a* (list 3 2 1))
  213.    (delete-if #'numberp *a) => NIL
  214.    *a* => (3 2 1)
  215.    (setq *a* nil *b* '(1 2 3))
  216.    (nconc *a* *b*) => (1 2 3)
  217.    *a* => NIL
  218.  
  219. The names of most destructure functions (except for sort, delete,
  220. rplaca, rplacd, and setf of accessor functions) have the prefix N.
  221.  
  222. In summary, the two common problems to watch out for when using
  223. destructive functions are:
  224.  
  225.    1. Forgetting to store the result back. Even though the list
  226.       is modified in place, it is still necessary to store the
  227.       result of the function back into the original location, e.g.,
  228.            (setq foo (delete 'x foo))
  229.  
  230.       If the original list was stored in multiple places, you may
  231.       need to store it back in all of them, e.g.
  232.            (setq bar foo)
  233.            ...
  234.            (setq foo (delete 'x foo))
  235.            (setq bar foo)
  236.  
  237.    2. Sharing structure that gets modified. If it is important
  238.       to preserve the shared structure, then you should either
  239.       use a nondestructive operation or copy the structure first
  240.       using COPY-LIST or COPY-TREE.
  241.            (setq bar (cdr foo))
  242.            ...
  243.            (setq foo (sort foo #'<))
  244.            ;;; now it's not safe to use BAR
  245.  
  246. Note that even nondestructive functions, such as REMOVE, and UNION,
  247. can return a result which shares structure with an argument. 
  248. Nondestructive functions don't necessarily copy their arguments; they
  249. just don't modify them.
  250.      
  251. ----------------------------------------------------------------
  252. Subject: [3-4] After I NREVERSE a list, it's only one element long.  
  253.                After I SORT a list, it's missing things.  What happened?
  254.  
  255. These are particular cases of the previous question.  Many NREVERSE and
  256. SORT implementations operate by rechaining all the CDR links in the list's
  257. backbone, rather than by replacing the CARs.  In the case of NREVERSE, this
  258. means that the cons cell that was originally first in the list becomes the
  259. last one.  As in the last question, the solution is to store the result
  260. back into the original location.
  261.      
  262. ----------------------------------------------------------------
  263. Subject: [3-5] Why does (READ-LINE) return "" immediately instead of 
  264.                waiting for me to type a line?
  265.  
  266. Many Lisp implementations on line-buffered systems do not discard the
  267. newline that the user must type after the last right parenthesis in order
  268. for the line to be transmitted from the OS to Lisp.  Lisp's READ function
  269. returns immediately after seeing the matching ")" in the stream.  When
  270. READLINE is called, it sees the next character in the stream, which is a
  271. newline, so it returns an empty line.  If you were to type "(read-line)This
  272. is a test" the result would be "This is a test".
  273.  
  274. The simplest solution is to use (PROGN (CLEAR-INPUT) (READ-LINE)).  This
  275. discards the buffered newline before reading the input.  However, it would
  276. also discard any other buffered input, as in the "This is a test" example
  277. above; some implementation also flush the OS's input buffers, so typeahead
  278. might be thrown away.
  279.  
  280. ----------------------------------------------------------------
  281. Subject: [3-6] I typed a form to the read-eval-print loop, but 
  282.                nothing happened. Why?
  283.  
  284. There's not much to go on here, but a common reason is that you haven't
  285. actually typed a complete form.  You may have typed a doublequote, vertical
  286. bar, "#|" comment beginning, or left parenthesis that you never matched
  287. with another doublequote, vertical bar, "|#", or right parenthesis,
  288. respectively.  Try typing a few right parentheses followed by Return.
  289.  
  290. ----------------------------------------------------------------
  291. Subject: [3-7]  DEFMACRO doesn't seem to work. 
  292.                 When I compile my file, LISP warns me that my macros
  293.                 are undefined functions, or complains 
  294.                   "Attempt to call <function> which is defined as a macro."
  295.  
  296. When you evaluate a DEFMACRO form or proclaim a function INLINE, it
  297. doesn't go back and update code that was compiled under the old
  298. definition. When redefining a macro, be sure to recompile any
  299. functions that use the macro. Also be sure that the macros used in a
  300. file are defined before any forms in the same file that use them.
  301.  
  302. Certain forms, including LOAD, SET-MACRO-CHARACTER, and
  303. REQUIRE, are not normally evaluated at compile time. Common Lisp
  304. requires that macros defined in a file be used when compiling later
  305. forms in the file. If a Lisp doesn't follow the standard, it may be
  306. necessary to wrap an EVAL-WHEN form around the macro definition.
  307.  
  308. Most often the "macro was previously called as a function" problem
  309. occurs when files were compiled/loaded in the wrong order. For
  310. example, developers may add the definition to one file, but use it in
  311. a file which is compiled/loaded before the definition. To work around
  312. this problem, one can either fix the modularization of the system, or
  313. manually recompile the files containing the forward references to macros.
  314.  
  315. Also, if your macro calls functions at macroexpand time, those functions
  316. may need to be in an EVAL-WHEN. For example,
  317.  
  318.     (defun some-function (x)
  319.       x)
  320.  
  321.     (defmacro some-macro (y)
  322.       (let ((z (some-function y)))
  323.         `(print ',z)))
  324.  
  325. If the macros are defined in a file you require, make sure your
  326. require or load statement is in an appropriate EVAL-WHEN. Many people
  327. avoid all this nonsense by making sure to load all their files before
  328. compiling them, or use a system facility (or just a script file) that
  329. loads each file before compiling the next file in the system.
  330.  
  331. ----------------------------------------------------------------
  332. Subject: [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  333.  
  334. If a package tries to export a symbol that's already defined, it will
  335. report an error. You probably tried to use a function only to discover
  336. that you'd forgotten to load its file. The failed attempt at using the
  337. function caused its symbol to be interned. So now, when you try to
  338. load the file, you get a conflict. Unfortunately, understanding and
  339. correcting the code which caused the export problem doesn't make those
  340. nasty error messages go away. That symbol is still interned where it
  341. shouldn't be. Use unintern to remove the symbol from a package before
  342. reloading the file. Also, when giving arguments to REQUIRE or package
  343. functions, use strings or keywords, not symbols: (find-package "FOO"),
  344. (find-package :foo). 
  345.  
  346. A sometimes useful technique is to rename (or delete) a package
  347. that is "too messed up".  Then you can reload the relevant files
  348. into a "clean" package.
  349.  
  350. ----------------------------------------------------------------
  351. Subject: [3-9]  Closures don't seem to work properly when referring to the
  352.                 iteration variable in DOLIST, DOTIMES and DO.
  353.  
  354. DOTIMES, DOLIST, and DO all use assignment instead of binding to
  355. update the value of the iteration variables. So something like
  356.    
  357.    (let ((l nil))
  358.      (dotimes (n 10)
  359.        (push #'(lambda () n)
  360.          l)))
  361.  
  362. will produce 10 closures over the same value of the variable N. To
  363. avoid this problem, you'll need to create a new binding after each
  364. assignment: 
  365.  
  366.    (let ((l nil))
  367.      (dotimes (n 10)
  368.     (let ((n n))
  369.       (push #'(lambda () n)
  370.         l))))
  371.  
  372. Then each closure will be over a new binding of n.
  373.  
  374. This is one reason why programmers who use closures prefer MAPC and
  375. MAPCAR to DOLIST.
  376.  
  377. ----------------------------------------------------------------
  378. Subject: [3-10] What is the difference between FUNCALL and APPLY?
  379.  
  380. FUNCALL is useful when the programmer knows the length of the argument
  381. list, but the function to call is either computed or provided as a
  382. parameter.  For instance, a simple implementation of MEMBER-IF (with
  383. none of the fancy options) could be written as:
  384.  
  385. (defun member-if (predicate list)
  386.   (do ((tail list (cdr tail)))
  387.       ((null tail))
  388.    (when (funcall predicate (car tail))
  389.      (return-from member-if tail))))
  390.  
  391. The programmer is invoking a caller-supplied function with a known
  392. argument list.
  393.  
  394. APPLY is needed when the argument list itself is supplied or computed.
  395. Its last argument must be a list, and the elements of this list become
  396. individual arguments to the function.  This frequently occurs when a
  397. function takes keyword options that will be passed on to some other
  398. function, perhaps with application-specific defaults inserted.  For
  399. instance:
  400.  
  401. (defun open-for-output (pathname &rest open-options)
  402.   (apply #'open pathname :direction :output open-options))
  403.  
  404. FUNCALL could actually have been defined using APPLY:
  405.  
  406. (defun funcall (function &rest arguments)
  407.   (apply function arguments))
  408.  
  409. ----------------------------------------------------------------
  410. Subject: [3-11] Miscellaneous things to consider when debugging code.
  411.  
  412. This question lists a variety of problems to watch out for when
  413. debugging code. This is sort of a catch-all question for problems too
  414. small to merit a question of their own. See also question [1-3] for
  415. some other common problems.
  416.  
  417. Functions:
  418.  
  419.   * (flet ((f ...)) (eq #'f #'f)) can return false.
  420.  
  421.   * The function LIST-LENGTH is not a faster, list-specific version
  422.     of the sequence function LENGTH.  It is list-specific, but it's
  423.     slower than LENGTH because it can handle circular lists.
  424.  
  425.   * Don't confuse the use of LISTP and CONSP. CONSP tests for the
  426.     presence of a cons cell, but will return NIL when called on NIL.
  427.     LISTP could be defined as (defun listp (x) (or (null x) (consp x))).
  428.  
  429.   * Use the right test for equality: 
  430.         EQ      tests if the objects are identical -- numbers with the
  431.                 same value need not be EQ, nor are two similar lists
  432.                 necessarily EQ. Similarly for characters and strings.
  433.                 For instance, (let ((x 1)) (eq x x)) is not guaranteed
  434.                 to return T.
  435.         EQL     Like EQ, but is also true if the arguments are numbers
  436.                 of the same type with the same value or character objects
  437.                 representing the same character. (eql -0.0 0.0) is not
  438.                 guaranteed to return T.
  439.         EQUAL   Tests if the arguments are structurally isomorphic, using
  440.                 EQUAL to compare components that conses, arrays, strings
  441.                 or pathnames, and EQ for all other data objects
  442.                 (except for numbers and characters, which are compared
  443.                 using EQL). 
  444.         EQUALP  Like EQUAL, but ignores type differences when comparing 
  445.                 numbers and case differences when comparing characters.
  446.         =       Compares the values of two numbers even if they are of
  447.                 different types.
  448.         CHAR=   Case-sensitive comparison of characters.
  449.         CHAR-EQUAL      Case-insensitive comparison of characters.
  450.         STRING= Compares two strings, checking if they are identical.
  451.                 It is case sensitive.
  452.         STRING-EQUAL  Like STRING=, but case-insensitive.
  453.  
  454.   * Some destructive functions that you think would modify CDRs might
  455.     modify CARs instead.  (E.g., NREVERSE.)
  456.  
  457.   * READ-FROM-STRING has some optional arguments before the
  458.     keyword parameters.  If you want to supply some keyword
  459.     arguments, you have to give all of the optional ones too.
  460.  
  461.   * If you use the function READ-FROM-STRING, you should probably bind
  462.     *READ-EVAL* to NIL. Otherwise an unscrupulous user could cause a
  463.     lot of damage by entering 
  464.         #.(shell "cd; rm -R *")
  465.     at a prompt.
  466.  
  467.   * Only functional objects can be funcalled in CLtL2, so a lambda
  468.     expression '(lambda (..) ..) is no longer suitable. Use
  469.     #'(lambda (..) ..) instead. If you must use '(lambda (..) ..),
  470.     coerce it to type FUNCTION first using COERCE.
  471.  
  472. Methods:
  473.  
  474.   * PRINT-OBJECT methods can make good code look buggy. If there is a
  475.     problem with the PRINT-OBJECT methods for one of your classes, it
  476.     could make it seem as though there were a problem with the object.
  477.     It can be very annoying to go chasing through your code looking for
  478.     the cause of the wrong value, when the culprit is just a bad
  479.     PRINT-OBJECT method.
  480.  
  481. Initialization:
  482.  
  483.   * Don't count on array elements being initialized to NIL, if you don't
  484.     specify an :initial-element argument to MAKE-ARRAY. For example,
  485.          (make-array 10) => #(0 0 0 0 0 0 0 0 0 0)
  486.  
  487. Iteration vs closures:
  488.  
  489.   * DO and DO* update the iteration variables by assignment; DOLIST and
  490.     DOTIMES are allowed to use assignment (rather than a new binding).
  491.     (All CLtL1 says of DOLIST and DOTIMES is that the variable "is
  492.     bound" which has been taken as _not_ implying that there will be
  493.     separate bindings for each iteration.) 
  494.  
  495.     Consequently, if you make closures over an iteration variable
  496.     in separate iterations they may nonetheless be closures over
  497.     the same variable and hence will all refer to the same value
  498.     -- whatever value the variable was given last.  For example,
  499.         (let ((fns '()))
  500.           (do ((x '(1 2) (cdr x)))
  501.               ((null x))
  502.             (push #'(lambda () x)
  503.                   fns))
  504.           (mapcar #'funcall (reverse fns)))
  505.     returns (nil nil), not (1 2), not even (2 2). Thus 
  506.          (let ((l nil)) 
  507.            (dolist (a '(1 2 3) l) 
  508.              (push #'(lambda () a)
  509.                    l)))
  510.     returns a list of three closures closed over the same bindings, whereas
  511.          (mapcar #'(lambda (a) #'(lambda () a)) '(1 2 3))
  512.     returns a list of closures over distinct bindings.
  513.  
  514. Defining Variables and Constants:
  515.  
  516.   * (defvar var init) assigns to the variable only if it does not
  517.     already have a value.  So if you edit a DEFVAR in a file and
  518.     reload the file only to find that the value has not changed,
  519.     this is the reason.  (Use DEFPARAMETER if you want the value
  520.     to change upon reloading.) DEFVAR is used to declare a variable
  521.     that is changed by the program; DEFPARAMETER is used to declare
  522.     a variable that is normally constant, but which can be changed
  523.     to change the functioning of a program.
  524.  
  525.   * DEFCONSTANT has several potentially unexpected properties:
  526.  
  527.      - Once a name has been declared constant, it cannot be used a
  528.        the name of a local variable (lexical or special) or function
  529.        parameter.  Really.  See page 87 of CLtL2.
  530.  
  531.      - A DEFCONSTANT cannot be re-evaluated (eg, by reloading the
  532.        file in which it appears) unless the new value is EQL to the
  533.        old one.  Strictly speaking, even that may not be allowed.
  534.        (DEFCONSTANT is "like DEFPARAMETER" and hence does an
  535.        assignment, which is not allowed if the name has already
  536.        been declared constant by DEFCONSTANT.)
  537.  
  538.        Note that this makes it difficult to use anything other
  539.        than numbers, symbols, and characters as constants.       
  540.  
  541.      - When compiling (DEFCONSTANT name form) in a file, the form
  542.        may be evaluated at compile-time, load-time, or both.  
  543.  
  544.        (You might think it would be evaluated at compile-time and
  545.        the _value_ used to obtain the object at load-time, but it
  546.        doesn't have to work that way.)
  547.  
  548. Declarations:
  549.  
  550.   * You often have to declare the result type to get the most
  551.     efficient arithmetic.  Eg, 
  552.  
  553.        (the fixnum (+ (the fixnum e1) (the fixnum e2)))
  554.  
  555.      rather than
  556.  
  557.        (+ (the fixnum e1) (the fixnum e2))
  558.  
  559.   * Declaring the iteration variable of a DOTIMES to have type FIXNUM
  560.     does not guarantee that fixnum arithmetic will be used.  That is,
  561.     implementations that use fixnum-specific arithmetic in the presence
  562.     of appropriate declaration may not think _this_ declaration is
  563.     sufficient.  It may help to declare that the limit is also a
  564.     fixnum, or you may have to write out the loop as a DO and add
  565.     appropriate declarations for each operation involved.
  566.  
  567. FORMAT related errors:
  568.  
  569.   * When printing messages about files, filenames like foo~ (a GNU-Emacs
  570.     backup file) may cause problems with poorly coded FORMAT control
  571.     strings.
  572.  
  573.   * Beware of using an ordinary string as the format string,
  574.     i.e., (format t string), rather than (format t "~A" string).
  575.  
  576. Miscellaneous:
  577.  
  578.   * Be careful of circular lists and shared list structure. 
  579.  
  580.   * Watch out for macro redefinitions.
  581.  
  582.   * A NOTINLINE may be needed if you want SETF of SYMBOL-FUNCTION to
  583.     affect calls within a file.  (See CLtL2, page 686.)
  584.  
  585.   * When dividing two numbers, beware of creating a rational number where
  586.     you intended to get an integer or floating point number. Use TRUNCATE
  587.     or ROUND to get an integer and FLOAT to ensure a floating point
  588.     number. This is a major source of errors when porting ZetaLisp or C
  589.     code to Common Lisp.
  590.  
  591.   * If your code doesn't work because all the symbols are mysteriously
  592.     in the keyword package, one of your comments has a colon (:) in
  593.     it instead of a semicolon (;).
  594.  
  595. ----------------------------------------------------------------
  596. Subject: [3-12] When is it right to use EVAL?
  597.  
  598. Hardly ever.  Any time you think you need to use EVAL, think hard about it.
  599. EVAL is useful when implementing a facility that provides an external
  600. interface to the Lisp interpreter.  For instance, many Lisp-based editors
  601. provide a command that prompts for a form and displays its value.
  602. Inexperienced macro writers often assume that they must explicitly EVAL the
  603. subforms that are supposed to be evaluated, but this is not so; the correct
  604. way to write such a macro is to have it expand into another form that has
  605. these subforms in places that will be evaluated by the normal evaluation
  606. rules.  Explicit use of EVAL in a macro is likely to result in one of two
  607. problems: the dreaded "double evaluation" problem, which may not show up
  608. during testing if the values of the expressions are self-evaluating
  609. constants (such as numbers); or evaluation at compile time rather than
  610. runtime.  For instance, if Lisp didn't have IF and one desired to write it,
  611. the following would be wrong:
  612.  
  613.    (defmacro if (test then-form &optional else-form)
  614.      ;; this evaluates all the subforms at compile time, and at runtime
  615.      ;; evaluates the results again.
  616.      `(cond (,(eval test) ,(eval then-form))
  617.             (t ,(eval else-form))))
  618.  
  619.    (defmacro if (test then-form &optional else-form)
  620.      ;; this double-evaluates at run time
  621.      `(cond ((eval ,test) (eval ,then-form))
  622.             (t (eval ,else-form)))
  623.  
  624. This is correct:
  625.  
  626.    (defmacro if (test then-form &optional else-form)
  627.      `(cond (,test ,then-form)
  628.             (t ,else-form)))
  629.  
  630. The following question (taken from an actual post) is typical of the
  631. kind of question asked by a programmer who is misusing EVAL:
  632.  
  633.    I would like to be able to quote all the atoms except the first in a
  634.    list of atoms.  The purpose is to allow a function to be read in and
  635.    evaluated as if its arguments had been quoted.
  636.  
  637. This is the wrong approach to solving the problem. Instead, he should
  638. APPLY the CAR of the form to the CDR of the form. Then quoting the
  639. rest of the form is unnecessary. But one wonders why he's trying to
  640. solve this problem in the first place, since the toplevel REP loop
  641. already involves a call to EVAL. One gets the feeling that if we knew
  642. more about what he's trying to accomplish, we'd be able to point out a
  643. more appropriate solution that uses neither EVAL nor APPLY.
  644.  
  645. On the other hand, EVAL can sometimes be necessary when the only portable
  646. interface to an operation is a macro. 
  647.  
  648. ----------------------------------------------------------------
  649. Subject: [3-13] Why does my program's behavior change each time I use it?
  650.  
  651. Most likely your program is altering itself, and the most common way this
  652. may happen is by performing destructive operations on embedded constant
  653. data structures.  For instance, consider the following:
  654.  
  655.    (defun one-to-ten-except (n)
  656.      (delete n '(1 2 3 4 5 6 7 8 9 10)))
  657.    (one-to-ten-except 3) => (1 2 4 5 6 7 8 9 10)
  658.    (one-to-ten-except 5) => (1 2 4 6 7 8 9 10) ; 3 is missing
  659.  
  660. The basic problem is that QUOTE returns its argument, *not* a copy of
  661. it. The list is actually a part of the lambda expression that is in
  662. ONE-TO-TEN-EXCEPT's function cell, and any modifications to it (e.g., by
  663. DELETE) are modifications to the actual object in the function definition.
  664. The next time that the function is called, this modified list is used.
  665.  
  666. In some implementations calling ONE-TO-TEN-EXCEPT may even result in
  667. the signalling of an error or the complete aborting of the Lisp process.  Some
  668. Lisp implementations put self-evaluating and quoted constants onto memory
  669. pages that are marked read-only, in order to catch bugs such as this.
  670. Details of this behavior may vary even within an implementation,
  671. depending on whether the code is interpreted or compiled (perhaps due to
  672. inlined DEFCONSTANT objects or constant folding optimizations).
  673.  
  674. All of these behaviors are allowed by the draft ANSI Common Lisp
  675. specification, which specifically states that the consequences of modifying
  676. a constant are undefined (X3J13 vote CONSTANT-MODIFICATION:DISALLOW).
  677.  
  678. To avoid these problems, use LIST to introduce a list, not QUOTE. QUOTE
  679. should be used only when the list is intended to be a constant which
  680. will not be modified.  If QUOTE is used to introduce a list which will
  681. later be modified, use COPY-LIST to provide a fresh copy.
  682.  
  683. For example, the following should all work correctly:
  684.  
  685.    o  (remove 4 (list 1 2 3 4 1 3 4 5))
  686.    o  (remove 4 '(1 2 3 4 1 3 4 5))   ;; Remove is non-destructive.
  687.    o  (delete 4 (list 1 2 3 4 1 3 4 5))
  688.    o  (let ((x (list 1 2 4 1 3 4 5)))
  689.         (delete 4 x))
  690.    o  (defvar *foo* '(1 2 3 4 1 3 4 5))
  691.       (delete 4 (copy-list *foo*))
  692.       (remove 4 *foo*)
  693.       (let ((x (copy-list *foo*)))
  694.          (delete 4 x))
  695.  
  696. The following, however, may not work as expected:
  697.  
  698.    o  (delete 4 '(1 2 3 4 1 3 4 5))
  699.  
  700. Note that similar issues may also apply to hard-coded strings. If you
  701. want to modify elements of a string, create the string with MAKE-STRING.
  702.  
  703. ----------------------------------------------------------------
  704. Subject: [3-14]  When producing formatted output in Lisp, where should you 
  705.         put the newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  706.         ~& vs ~% in FORMAT)?
  707.  
  708.  
  709. Where possible, it is desirable to write functions that produce output
  710. as building blocks. In contrast with other languages, which either
  711. conservatively force a newline at various times or require the program
  712. to keep track of whether it needs to force a newline, the Lisp I/O
  713. system keeps track of whether the most recently printed character was
  714. a newline or not. The function FRESH-LINE outputs a newline only if
  715. the stream is not already at the beginning of a line.  TERPRI forces a
  716. newline irrespective of the current state of the stream. These
  717. correspond to the ~& and ~% FORMAT directives, respectively. (If the
  718. Lisp I/O system can't determine whether it's physically at the
  719. beginning of a line, it assumes that a newline is needed, just in case.)
  720.  
  721. Thus, if you want formatted output to be on a line of its own, start
  722. it with ~& and end it with ~%. (Some people will use a ~& also at the
  723. end, but this isn't necessary, since we know a priori that we're not
  724. at the beginning of a line. The only exception is when ~& follows a
  725. ~A, to prevent a double newline when the argument to the ~A is a
  726. formatted string with a newline at the end.) For example, the
  727. following routine prints the elements of a list, N elements per line,
  728. and then prints the total number of elements on a new line:
  729.  
  730.    (defun print-list (list &optional (elements-per-line 10))
  731.      (fresh-line)
  732.      (loop for i upfrom 1
  733.            for element in list do
  734.        (format t "~A ~:[~;~%~]" element (zerop (mod i elements-per-line))))
  735.      (format t "~&~D~%" (length list)))
  736.  
  737. ----------------------------------------------------------------
  738. Subject: [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  739.  
  740. Your code probably looks something like
  741.    (do ((sublist list (cdr list))
  742.         ..)
  743.        ((endp sublist)
  744.         ..)
  745.      ..)
  746. or maybe
  747.    (do ((index start (+ start 2))
  748.         ..)
  749.        ((= index end)
  750.         ..)
  751.      ..)
  752.  
  753. The problem is caused by the (cdr list) and the (+ start 2) in the
  754. first line. You're using the original list and start index instead of
  755. the working sublist or index. Change them to (cdr sublist) and 
  756. (+ index 2) and your code should start working.
  757.  
  758. ----------------------------------------------------------------
  759. Subject: [3-16] My program works when interpreted but not when compiled!
  760.  
  761. Look for problems with your macro definitions, such as a macro that is
  762. missing a quote. When compiled, this definition essentially becomes a
  763. constant. But when interpreted, the body of the macro is executed each
  764. time the macro is called.
  765.  
  766. For example, in Allegro CL the following code will behave differently
  767. when interpreted and compiled:
  768.   (defvar x 10)
  769.   (defmacro foo () (incf x))
  770.   (defun bar () (+ (foo) (foo)))
  771. Putting a quote before the (incf x) in the definition of foo fixes the
  772. problem. 
  773.  
  774. If you use (SETF (SYMBOL-FUNCTION 'foo) ...) to change the definition
  775. of a built-in Lisp function named FOO, be aware that this may not work
  776. correctly (i.e., as desired) in compiled code in all Lisps. In some
  777. Lisps, the compiler treats certain symbols in the LISP package
  778. specially, ignoring the function definition. If you want to redefine a
  779. standard function try proclaiming/declaring it NOTINLINE prior to
  780. compiling any use that should go through the function cell. (Note that
  781. this is not guarranteed to work, since X3J13 has stated that it is not
  782. permitted to redefine any of the standard functions).
  783.  
  784. ----------------------------------------------------------------
  785. ;;; *EOF*
  786.